﻿#if WINDOWS_PHONE
using System;
using System.Device.Location;
using System.Diagnostics;
using System.Threading.Tasks;
#endif

namespace MoneyLover.Service
{
    public class LocationService
    {

#if WINDOWS_PHONE

        GeoCoordinateWatcher _watcher;
        public GeoCoordinate CurrentLocation;
        public event EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>> PositionChanged;

        public static bool Loaded = false;

        public LocationService()
        {
            try
            {
                _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High) { MovementThreshold = 10 };
                _watcher.StatusChanged += OnStatusChanged;
                _watcher.PositionChanged += OnPositionChanged;
                _watcher.Start();
            }
            catch { }
        }

        void OnStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            try
            {
                if (e.Status == GeoPositionStatus.Disabled)
                    Debug.WriteLine("The location service is currently turned off.");
                else if (e.Status == GeoPositionStatus.NoData)
                    Debug.WriteLine("No location data is currently available. Try again later.");
                Loaded = true;
            }
            catch { }
        }

        void OnPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            try
            {
                CurrentLocation = e.Position.Location;
                PositionChanged(sender, e);
            }
            catch { }
        }

        public Task<GeoCoordinate> WaitForChanges()
        {
            var tcs = new TaskCompletionSource<GeoCoordinate>();
            _watcher.PositionChanged += (a1, e1) =>
            {
                CurrentLocation = e1.Position.Location;
                tcs.TrySetResult(e1.Position.Location);
            };
            return tcs.Task;
        }

#else

#endif
    }
}